<template>
  <base-container>
    <!-- 搜索栏 -->
    <avue-table-search
      :option="searchOption"
      v-model="searchParams"
      @search-change="loadTableSearch"
      @search-reset="loadTableSearchReset"
    />
    <!-- 卡片容器 -->
    <base-table-card>
      <template #header-right>
        <el-button type="primary" @click="handleOpenAddDialog">开通{{ serviceData.serviceName }}</el-button>
        <el-button :style="{ marginBottom: '0px' }" class="btn" color="#5947F1" plain @click="handleOpenEditDialog"
          >编辑套餐</el-button
        >
      </template>
      <!-- <template #header-right>
        <div>
          <span :style="{ marginRight: '20px' }">{{ serviceData.smsInfo }}</span>
          <span></span>
          <span :style="{ color: '#5947f1', cursor: 'pointer' }" @click="handleOpenEditDialog">编辑套餐</span>
        </div>
      </template> -->
      <avue-crud
        ref="avueCrudRef"
        :option="tableOption"
        :data="tableData"
        v-model="formData"
        :page="page"
        :table-loading="tableLoading"
        :before-open="handleBeforeOpen"
        @refresh-change="loadGetTableData"
        @current-change="loadTablePageChange"
        @size-change="loadTablePageSizeChange"
        @row-save="loadAdd"
        @row-update="loadEdit"
      >
        <!-- 展示状态开关 -->
        <template #status="{ row }">
          <el-switch
            :model-value="row.status"
            :loading="row.statusLoading"
            :active-value="1"
            :inactive-value="2"
            :before-change="() => handleStatusBeforeChange(row)"
          />
        </template>
        <template #tenantId-form>
          <el-select
            v-if="!rowId"
            v-model="formData.tenantId"
            filterable
            remote
            placeholder="请输入客户ID搜索"
            :remote-method="loadRemoteMethod"
            :loading="selectLoading"
          >
            <el-option v-for="item in tenantIdOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
          <div v-else>{{ formData.tenantName }}</div>
        </template>
        <template #configParams-form>
          <div class="configParams-content">
            <el-row class="configParams-row" v-for="(item, index) in formData.configParams" :key="index">
              <el-col class="configParams-col" :span="24">
                <div class="configParams-label-content">
                  <span class="star">*</span>
                  <span class="configParams-label">{{ item.key }}:</span>
                </div>
                <el-input :style="{ flex: 3.7 }" maxlength="100" v-model="item.value" placeholder="请输入参数" />
              </el-col>
            </el-row>
          </div>
        </template>

        <template #menu="{ row }">
          <el-button type="primary" text @click="handleEdit(row)">编辑</el-button>
        </template>
      </avue-crud>
    </base-table-card>
    <!-- 使用 BaseDialog -->
    <BaseDialog
      v-model="showDialog"
      title="设置套餐"
      width="600px"
      :show-footer="true"
      :show-cancel="false"
      confirm-text="确定新增"
      @confirm="handleConfirm"
    >
      <div class="sticky-header">
        <el-tabs v-model="tabActive" @tab-change="handTabsChange">
          <el-tab-pane
            :label="item.description"
            :name="item.type"
            v-for="(item, index) in smsTypeOptions"
            :key="index"
          />
        </el-tabs>
      </div>
      <div class="dialog-content">
        <el-button class="btn" color="#5947F1" plain @click="handAddFormList">增加套餐</el-button>
        <el-form ref="formRef" :model="form" label-width="120px" label-position="top">
          <div v-for="(val, index) in form.smsList" :key="index">
            <div class="typeName">{{ val.typeName }}</div>
            <div>
              <el-form-item
                :prop="`smsList.${index}.quantity`"
                label="短信数量（条）"
                :rules="[
                  {
                    required: true,
                    message: '请输入短信数量',
                    trigger: 'blur',
                  },
                ]"
              >
                <el-input clearable v-model="val.quantity" />
              </el-form-item>
              <el-form-item
                :prop="`smsList.${index}.price`"
                label="套餐价格（元）"
                :rules="[
                  {
                    required: true,
                    message: '请输入套餐价格',
                    trigger: 'blur',
                  },
                ]"
              >
                <el-input clearable v-model="val.price" />
              </el-form-item>
              <el-form-item
                :prop="`smsList.${index}.cost`"
                label="套餐成本（元）"
                :rules="[
                  {
                    required: true,
                    message: '请输入套餐成本',
                    trigger: 'blur',
                  },
                ]"
              >
                <el-input clearable v-model="val.cost" />
              </el-form-item>
            </div>
          </div>
        </el-form>
      </div>
    </BaseDialog>
  </base-container>
</template>

<script setup>
  import useCrudHook from "avue-table/useCrudHook";
  import Option from "@/crudOption/application/sms";
  const showDialog = ref(false);
  const tabActive = ref("");
  const rowId = ref("");
  // 获取全局方法
  const App = getCurrentInstance().appContext.config.globalProperties;
  let serviceId = "";
  onMounted(() => {
    const route = useRoute();
    serviceId = route.path.split("/").filter(Boolean).pop();
    searchParams.value.id = serviceId;
    // 获取表格数据
    loadGetTableData();
    // 获取基础信息，判断开通按钮是否展示
    loadBasicsInfo();
  });
  const handleStatusBeforeChange = row => {
    return new Promise((resolve, reject) => {
      App.$confirm(`是否确认${row.status === 1 ? "关闭" : "开通"}？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const status = row.status === 1 ? 2 : 1; // 先取反
          row.statusLoading = true;
          Api.application
            .serviceProviderEnable({ id: row.id, status: status })
            .then(() => {
              // 操作结果
              $msg.success(status ? "关闭成功" : "开通成功");
              // 刷新状态数据
              row.status = status;
              // 操作成功，切换状态
              resolve(true);
            })
            .catch(() => {
              // 操作失败，保持原状态
              reject(false);
            })
            .finally(() => {
              row.statusLoading = false;
            });
        })
        .catch(() => {
          // 取消操作，保持原状态
          reject(false);
        });
    });
  };
  // 通过客户ID获取客户
  const selectLoading = ref(false);
  const tenantIdOptions = ref([]);
  async function loadRemoteMethod(query) {
    console.log("🚀 ~ loadRemoteMethod ~ query:", query);
    if (!query) return;
    selectLoading.value = true;
    const res = await Api.application.getCustomerByTenantId({ tenantId: query });
    console.log("🚀 ~ loadRemoteMethod ~ res:", res);
    selectLoading.value = false;
    if (res.code == "200" && res.data) {
      tenantIdOptions.value = [
        {
          value: res.data.tenantId,
          label: res.data.customerName,
        },
      ];
    }
  }

  // avue-crud 组件实例
  const avueCrudRef = ref({});

  // 增删改查 hook
  let {
    data: tableData,
    loading: tableLoading,
    page: page,
    search: searchParams,
    form: formData,
    get: loadGetTableData,
    add: loadAdd,
    edit: loadEdit,
    pageNumChange: loadTablePageChange,
    pageSizeChange: loadTablePageSizeChange,
    searchReset: loadTableSearchReset,
    searchChange: loadTableSearch,
  } = useCrudHook({
    get: Api.application.servicePage,
    add: Api.application.serviceAddSms,
    edit: Api.application.serviceUpdateSms,
    dataRes: "data.records",
    // dataFormat: res => {
    //   console.log("🚀 ~ res:", res);
    //   appName.value = res.data.page.records[0].appName;
    //   return res.data.page.records;
    // },
    addParamsFormat: row => ({
      ...row,
      serviceId: searchParams.value.id,
      tenantName: tenantIdOptions.value.find(item => item.value === row.tenantId)?.label,
    }),
    editParamsFormat: row => ({
      ...row,
    }),
  });
  // 获取 搜索配置 和 表格配置
  const { searchOption, tableOption } = Option(formData);

  // 获取基础信息，判断开通按钮是否展示
  const serviceData = ref({});
  async function loadBasicsInfo() {
    const res = await Api.application.basicsInfo({ id: searchParams.value.id });
    console.log("🚀 ~ loadBasicsInfo ~ res:", res);
    if (res.code == "200" && res?.data) {
      serviceData.value = res.data;
      tableOption.value.addTitle = `开通${res.data.serviceName}`;
      tableOption.value.editTitle = `编辑${res.data.serviceName}`;
    }
  }
  const form = ref({
    smsList: [],
  });
  const typeName = ref(""); // 短信套餐类型名称
  // 短信套餐类型
  const smsTypeOptions = ref([]);
  async function loadSmsTypeList() {
    const res = await Api.application.smsTypeList();
    console.log("🚀 ~ loadBasicsInfo ~ res:", res);
    if (res.code == "200" && res?.data?.length > 0) {
      showDialog.value = true;
      smsTypeOptions.value = res.data;
      // 短信套餐列表
      loadSmsList(res.data[0].type);
      tabActive.value = res.data[0].type;
      typeName.value = res.data[0].description;
    }
  }
  // 短信套餐列表
  async function loadSmsList(type) {
    const res = await Api.application.smsList({ serviceId: searchParams.value.id, smsType: type });
    // console.log("🚀 ~ loadBasicsInfo ~ res:", res);
    if (res.code == "200" && res?.data?.length > 0) {
      form.value.smsList = res.data;
    }
  }
  // 弹窗打开前
  const handleBeforeOpen = done => {
    nextTick(done);
  };

  // 已移除无关的菜单树逻辑

  // 打开新增弹窗
  const handleOpenAddDialog = () => {
    // formData.value = { ...formData.value };
    rowId.value = "";
    avueCrudRef.value.rowAdd();
  };
  // 编辑套餐
  async function handleOpenEditDialog() {
    // 获取短信套餐类型
    await loadSmsTypeList();
  }
  // 短信套餐类型tab切换
  function handTabsChange(val) {
    smsTypeOptions.value.forEach(item => {
      if (item.type == val) {
        typeName.value = item.description;
      }
    });
    loadSmsList(val);
  }
  function handAddFormList() {
    form.value.smsList.push({ quantity: "", price: null, cost: null, typeName: typeName.value });
  }
  const formRef = ref();
  // 设置套餐
  function handleConfirm() {
    formRef.value.validate(isValid => {
      console.log("🚀 ~ handleConfirm ~ isValid:", isValid);
      if (isValid) {
        Api.application
          .serviceAddOrUpdate({
            itemBackendRQList: form.value.smsList,
            serviceId: searchParams.value.id,
          })
          .then(() => {
            App.$message.success("设置成功");
            showDialog.value = false;
            loadGetTableData();
          });
      }
    });
  }
  // 编辑时回显数据
  function handleEdit(row) {
    rowId.value = row.id;
    // console.log("🚀 ~ handleEdit ~ paths:", paths);
    avueCrudRef.value?.rowEdit({
      ...row,
    });
  }
</script>

<style lang="scss" scoped>
  .configParams-label-content {
    width: 120px;
    text-align: right;
    color: #49446d;
    padding-right: 12px;
    line-height: 1.2;
    flex: 1;
    .star {
      color: #f33d3d;
      padding-right: 4px;
      vertical-align: middle;
      margin-top: 3px;
    }
  }
  .configParams-row {
    margin-bottom: 18px;
  }
  .configParams-col {
    display: flex;
    align-items: center;
  }
  .btn {
    background-color: #fff;
    margin-bottom: 16px;
  }
  .btn:hover {
    color: #5947f1;
  }
  .typeName {
    color: #1c174d;
    font-family: PingFang SC;
    font-weight: bold;
    margin-bottom: 16px;
    font-size: 14px;
    line-height: 22px;
  }
</style>
